<?php
/**
 * 员工
 * 
 * Created  : 2011-05-23
 * Modified : 2011-05-24
 * @author  : 陈立强
 */
class Staff
{
	public static $cfg = null;
	public static $cfgName = 'making/staff';
	
	/**
	 * 获取一个制造类型的员工信息
	 * @param int $uid
	 * @param int $class
	 */
	public static function getInfo($uid, $class)
	{
		global $DB, $L, $G;
		
		$class = (int)$class;
		
		$sql = 'SELECT * FROM staff WHERE uid='.$uid.' and class='.$class;
		$staffInfo = $DB->getValue($sql);
		if (!$staffInfo) {
			return $staffInfo;
		}
		$today = strtotime('today');
		// 上次刷新状态值时间不是当天则更新状态值和更新时间
		if ($staffInfo['last_state_refresh_time'] < $today) {
			$stateVal = $G['staff_state_val'];
			$data = array(
				'state_val'					=> rand($stateVal[0], $stateVal[1]),
				'state_refresh_times'		=> 0,
				'last_state_refresh_time'	=> $today
			);
			$ret = $DB->update('staff', $staffInfo, 'staff_id='.$staffInfo['staff_id']);
		}
		
		$staffInfo['card_list'] = self::getCardList($uid, $staffInfo['staff_id'], $staffInfo);
		$staffInfo['card_mat_list'] = self::getCardMatList($uid, $staffInfo['staff_id'], $staffInfo);
		
 		for ($i=0; $i<=5; $i++) {
			unset($staffInfo['card'.$i]);
		}
		
		return $staffInfo;
	}
	
	/**
	 * 获取一个员工信息
	 * @param int $uid
	 * @param int $staff_id
	 */
	public static function getInfoById($uid, $staff_id)
	{
		global $DB, $L, $G;
		
		$staff_id = (int)$staff_id;
		
		$sql = 'SELECT * FROM staff WHERE staff_id='.$staff_id;
		$staffInfo = $DB->getValue($sql);
		if (!$staffInfo) {
			return $staffInfo;
		}
		$today = strtotime('today');
		// 上次刷新状态值时间不是当天则更新状态值和更新时间
		if ($staffInfo['last_state_refresh_time'] < $today) {
			$staffInfo['state_val'] = rand($G['staff_state_val'][0], $G['staff_state_val'][1]);
			$staffInfo['state_refresh_times'] = 0;
			$staffInfo['last_state_refresh_time'] = $today;
			$ret = $DB->update('staff', $staffInfo, 'staff_id='.$staff_id);
		}
		
		$staffInfo['card_list'] = self::getCardList($uid, $staff_id, $staffInfo);
		$staffInfo['card_mat_list'] = self::getCardMatList($uid, $staff_id, $staffInfo);
		
		for ($i=0; $i<=5; $i++) {
			unset($staffInfo['card'.$i]);
		}
		
		return $staffInfo;
	}
	
	/**
	 * 获取一个员工的卡片信息
	 * @param int $uid
	 * @param int $staff_id
	 * @param array $staffInfo 员工信息
	 */
	private static function getCardMatList($uid)
	{
		global $DB, $L, $G;
		$sql = 'SELECT num,lvl FROM bag WHERE uid='.$uid.' AND (item_id BETWEEN 10011 AND 10015)';
		$_list = $DB->getList($sql);
		$list = array();
		foreach ($_list as $v) {
			$list[$v['lvl']] = $v['num'];
		}
		
		return $list;
	}
	
	/**
	 * 获取一个员工的卡片信息
	 * @param int $uid
	 * @param int $staff_id
	 * @param array $staffInfo 员工信息
	 */
	private static function getCardList($uid, $staff_id, $staffInfo)
	{
		global $DB, $L, $G;
	
		// 获取卡片信息
		$sql = 'SELECT bag_id,item_id,item_type,title,lvl,status,staff_id,part,attr
				FROM bag WHERE staff_id='.$staff_id
				.' AND status=3 AND item_type=54';
		$_cardList = $DB->getList($sql);
		$cardList = array();
		foreach ($_cardList as $v) {
			$v['pos'] = $v['part'];
			if ($v['attr']) {
				$_tmp = json_decode($v['attr'], true);
				$v = array_merge($v, $_tmp);
				unset($v['attr']);
			}
			$cardList[$v['pos']] = $v;
		}
		$itemList = C('item/other');
		for ($i=1; $i<=5; $i++) {
			if (!isset($cardList[$i])) {
				if ($staffInfo['card'.$i]) {
					$cardList[$i] = array(
						'item_id'	=> $staffInfo['card'.$i],
						'item_type'	=> 54,
						'title'		=> $itemList[$staffInfo['card'.$i]]['title'],
						'lvl'		=> 0,
						'staff_id'	=> $staff_id,
						'status'	=> 2,
						'pos'		=> $i,
					);
				} else {
					// 初始默认0级剪刀(item_id:10022)
					$cardList[$i] = array (
						'item_id'	=> 10022,
						'item_type'	=> 54,
						'title'		=> $itemList[10022]['title'],
						'lvl'		=> 0,
						'staff_id'	=> $staff_id,
						'status'	=> 2,
						'pos'		=> $i,
					);
				}
			}
		}
		
		ksort($cardList);
		
		return $cardList;
	}
	
	/**
	 * 将卡片放在卡片槽中
	 * @param int $uid
	 * @param int $staff_id
	 * @param int $card_id 卡片在背包的ID
	 * @param int $pos
	 * @param int $item_id 当用0级卡片替代时,该参数为0级卡片对应的ID
	 */
	public static function putOnCard($uid, $staff_id, $card_id, $pos, $item_id=0)
	{
		global $DB, $L, $G;
		
		$staff_id	= (int)$staff_id;
		$card_id	= (int)$card_id;
		$pos		= (int)$pos;
		if ($card_id) {
			$item_id = 0;
		} else {
			$item_id	= (int)$item_id;
		}
		
		$DB->beginTransaction();
		
		if ($card_id) {// 背包中真实卡片放上去
			$sql = 'SELECT * FROM bag WHERE bag_id='.$card_id;
			$itemInfo = $DB->getValue($sql);
			// 卡片不属于当前玩家
			if ($itemInfo['uid'] != $uid) {
				return array(
					'val' => false,
					'msg' => $L['invalid_request']
				);
			}
			// 卡片状态不在背包中
			if ($itemInfo['status']!=1) {
				return array(
					'val' => false,
					'msg' => $L['invalid_request']
				);
			}
		
		} else {
			$itemList = C('item/other');
			$itemInfo = $itemList[$item_id];
			// 给出物品模板ID不是卡片
			if ($itemInfo['item_type'] != 54) {
				return array(
					'val' => false,
					'msg' => $L['invalid_request']
				);
			}
			
		}
		
		$sql = 'SELECT * FROM staff WHERE staff_id='.$staff_id;
		$staffInfo = $DB->getValue($sql);
		if ($staffInfo['uid'] != $uid) {
			return array(
				'val' => false,
				'msg' => $L['invalid_request']
			);
		}
		
		
		// 员工当前槽位上的卡片信息(更新)
		if ($staffInfo['card'.$pos]) {// 当前槽位有0级卡片
			$ret = true;
		} else { // 当前槽位是一个真实的卡片,要存回背包(对应位置ID为0)
			$sql = 'SELECT bag_id,status FROM bag WHERE staff_id='.$staff_id.' AND item_type=54 '
					.' AND part='.$pos;
			$nowCard = $DB->getValue($sql);
			$data = array(
				'status'	=> 1,
				'staff_id'	=> 0,
				'part'		=> 0,
			);
			$ret = $DB->update('bag', $data, 'bag_id='.$nowCard['bag_id']);
		}
		
		// 穿上的卡片信息更新 
		if ($card_id) {
			$data = array(
				'status'	=> 3,
				'staff_id'	=> $staff_id,
				'part'		=> $pos
			);
			$ret = $DB->update('bag', $data, 'bag_id='.$itemInfo['bag_id']);
		}
		// 背包中卡片的状态信息更新
		if ($ret) {
			$data = array(
				'card'.$pos	=> $item_id
			);
			$ret = $DB->update('staff', $data, 'staff_id='.$staff_id);
		}
		
		$result['val'] = (boolean)$ret;
		if ($ret) {
			$DB->commit();
			$result['data'] = self::getInfoById($uid, $staff_id);
		} else {
			$DB->rollBack();
			$result['msg'] = $L['Failure_Update'];
			$str = var_export($DB->errors, true);
			// 记录错误日志
			Log::save('staff_put_on_card', $str);
		}
		
		return $result;
		
	}
	
	/**
	 * 获取0级卡片列表
	 * @param $uid
	 */
	public static function getDefaultCardList($uid)
	{
		global $L, $G;
		
		$itemList = C('item/other');
		$list = array();
		foreach ($itemList as $item_id=>$item) {
			if ($item['item_type'] != 54) {
				continue;
			}
			$list[] = array(
				'item_id'	=> $item_id,
				'title'		=> $item['title'],
				'item_type'	=> $item['item_type'],
				'lvl'		=> 0,
			);
		}
		
		return array(
			'val'	=> true,
			'data'	=> $list
		);
	}
	
	/**
	 * 获取一个制造类型的员工能力值数据
	 * @param int $uid
	 * @param int $class
	 * @param int $abi_id
	 * @return array
	 */
	public static function getData($uid, $class, $abi_id=null)
	{
		global $DB, $L, $G;
		
		$sql = 'SELECT * FROM staff_data WHERE uid='.$uid.' AND class='.(int)$class;
		if (!empty($abi_id)) {
			$sql .= ' AND abi_id='.(int)$abi_id;
			$staffData = $DB->getValue($sql);
		} else {
			$itemList = C('item/item_list');
			C('build/making');
			$staffData = $DB->getList($sql);
			foreach ($staffData as $k=>$v) {
				$staffData[$k]['title'] = $itemList[$v['abi_id']]['title'];
				$staffData[$k]['type']  = $G['product_type_list'][$v['abi_id']];
			}
		}
		
		return $staffData;
	}
	
	/**
	 * 获取员工能力值数据
	 * @param int $uid
	 * @param int $class
	 * @param int $abi_id
	 * @return array
	 */
	public static function getDataById($uid, $staff_id, $abi_id=null)
	{
		global $DB, $L, $G;
		$sql = 'SELECT * FROM staff_data WHERE staff_id='.$staff_id;
		if (!is_null($abi_id)) {
			$sql .= ' AND abi_id='.(int)$abi_id;
		}
		$staffData = $DB->getValue($sql);
		if ($staffData)
		
		return $staffData;
	}
	
	/**
	 * 给一个工作区增加一名员工
	 * @param int $uid
	 * @param int $type
	 */
	public static function add($uid, $class)
	{
		global $DB, $L, $G;
		
		$sql = 'SELECT * FROM staff WHERE uid='.$uid.' and class='.$class;
		$staffInfo = $DB->getValue($sql);
		if ($staffInfo) {
			return false;
		}
		
		$name = self::randName();
		
		$DB->beginTransaction();
		
		$data = array(
			'uid'  => $uid,
			'class'=> $class,
			'name' => $name,
			'exp'  => 0,
			'train_times'   => $G['init_train_times'],
			'total_abi_val' => 0,
			'potential_lvl'	=> 0,
			'max_recipe_num'=> $G['init_max_recipe_num'],
			'state_val'		=> rand($G['staff_state_val'][0], $G['staff_state_val'][1]),
			'state_refresh_times'		=> 0,
			'last_state_refresh_time'	=> time(),
			// 员工卡片槽默认0级剪刀
			'card1'	=> 10022,
			'card2'	=> 10022,
			'card3'	=> 10022,
			'card4'	=> 10022,
			'card5'	=> 10022,
		);
		$staff_id = $ret = $DB->insert('staff', $data);
		$total_abi_val = 0;// 能力总和
		
		if ($ret) {
			C('build/making');
			$sign = $G['make_class_type_sign_list'][$class];
			$list = $G[$sign];
			// 初始能力值总和是固定的,剩余初始值
			$remain_abi_val = $G['init_abi_val_total'];
			// 能力数
			$abi_num = count($list);
		
			// 能力数
			$abi_num = count($list);
			$times = 0;
			while(true) {
				$times++;
				$abiValList = array();
				for ($i=1; $i<$abi_num; $i++) {
					$abiValList[] = rand($G['init_abi_val'][0], $G['init_abi_val'][1]);
				}
				$sum = array_sum($abiValList);
				$remain = $G['init_abi_val_total'] - $sum;
				if ($remain > $G['init_abi_val'][0] && $remain < $G['init_abi_val'][1]) {
					$abiValList[] = $remain;
					break;
				}
			}
			foreach ($abiValList as $k=>$val) {
				$data = array(
					'staff_id'	=> $staff_id,
					'uid'		=> $uid,
					'class'		=> $class,
					'abi_id'	=> $list[$k+1]['item_id'],
					'abi_val'	=> $val,
				);
				$total_abi_val += $val;
				$ret = $DB->insert('staff_data', $data);
			}
		}
		
		if ($ret) {
			$data = array(
				'total_abi_val' => $total_abi_val
			);
			$ret = $DB->update('staff', $data, 'staff_id='.$staff_id);
			$ret !== false && $ret = true;
		}
		
		// 增加员工初始配方
		if ($ret) {
			$classSign = $G['make_class_type_sign_list'][$class];
			$ret = Making::saveRecipe(
				$uid, 
				$L['init_recipe_title'][$classSign], 
				$classSign, 
				$G['init_recipe'][$classSign]['product'], 
				$G['init_recipe'][$classSign]['technics'], 
				$G['init_recipe'][$classSign]['param'], 
				$G['init_recipe'][$classSign]['main_mat'], 
				$G['init_recipe'][$classSign]['sec_mat']
			);
			$ret = $ret['val'];
		}
		
		$result['val'] = (boolean)$ret;
		if ($ret) {
			$DB->commit();
			$result['data'] = $data;
		} else {
			$DB->rollBack();
			$result['msg'] = $L['Failure_Update'];
			$str = var_export($DB->errors, true);
			// 记录错误日志
			Log::save('staff_add', $str);
		}
		
		return $ret;
	}
	
	/**
	 * 随机一个员工姓名
	 */
	public static function randName()
	{
		$staffNameList = C('making/staff_name');
		$size = count($staffNameList['family_name']);
		$key = rand(0, $size-1);
		$familyName = $staffNameList['family_name'][$key];
		
		$size = count($staffNameList['given_name']);
		$key = rand(0, $size-1);
		$givenName = $staffNameList['given_name'][$key];
		
		return $givenName.'·'.$familyName;
	}
	
	/**
	 * 刷新员工状态值
	 * @param int $uid
	 * @param int $staff_id
	 */
	public static function refreshStateVal($uid, $staff_id)
	{
		global $DB, $L, $G;
		
		$staff_id = (int)$staff_id;
		
		$sql = 'SELECT * FROM staff WHERE staff_id='.$staff_id;
		$staffInfo = $DB->getValue($sql);
		if ($uid != $staffInfo['uid']) {
			return array(
				'val' => false,
				'msg' => $L['invalid_request']
			);
		}
		
		// 消耗金钱
		$needCoin = $G['refresh_state_val_base_coin'] + 
				($staffInfo['state_refresh_times'] * 10);
		
		$where = ' uid='.$uid;
		$sql = 'SELECT coin FROM user WHERE '.$where;
		$coin = $DB->getValue($sql);
		
		if ($needCoin > $coin) {
			return array(
				'val' => false,
				'msg' => $L['coin_not_enough']
			);
		}
		
		$stateVal = rand($G['staff_state_val'][0], $G['staff_state_val'][1]);
		
		$DB->beginTransaction();
		
		$sql = 'UPDATE user set coin=coin-'.$needCoin.' WHERE '.$where;
		$ret = $DB->exeSql($sql);
		
		if ($ret) {
			$data = array(
				'state_val'				=> $stateVal,
				'state_refresh_times'	=> $staffInfo['state_refresh_times'] + 1,
				'last_state_refresh_time'=> time(),
			);
			$ret = $DB->update('staff', $data, 'staff_id='.$staff_id);
		}
		
		
		$result['val'] = (boolean)$ret;
		if ($ret) {
			$DB->commit();
			$result['data'] = array_merge($staffInfo, $data);
		} else {
			$DB->rollBack();
			$result['msg'] = $L['Failure_Update'];
			$str = var_export($DB->errors, true);
			// 记录错误日志
			Log::save('staff_lvl_up', $str);
		}
		
		return $result;
		
	}
	
	/**
	 * 升级
	 * @param int $uid
	 * @param int $staff_id
	 */
	public static function lvlUp($uid, $staff_id)
	{
		global $DB, $L, $G;
		
		$staff_id = (int)$staff_id;
		
		$maxLvl = end($G['potential_lvl_list']);
		if ($lvl == $maxLvl) {
			return array(
				'val' => false,
				'msg' => $L['potential_is_max_lvl']
			);
		}
		
		$sql = 'SELECT * FROM staff WHERE staff_id='.$staff_id;
		$staffInfo = $DB->getValue($sql);
		if ($uid != $staffInfo['uid']) {
			return array(
				'val' => false,
				'msg' => $L['invalid_request']
			);
		}
		
		$sql = 'SELECT coin FROM user WHERE uid='.$uid;
		$coin = $DB->getValue($sql);
		
		$cfg = $G['potential_lvl_list'][$staffInfo['potential_lvl']];
		
		if ($cfg['need_coin'] > $coin) {
			return array(
				'val' => false,
				'msg' => $L['coin_not_enough']
			);
		}
		
		if ($cfg['need_exp'] > $staffInfo['exp']) {
			return array(
				'val' => false,
				'msg' => $L['potential_exp_not_enough']
			);
		}
		
		$DB->beginTransaction();
		
		// 升级并扣经验
		$sql = 'UPDATE staff SET potential_lvl=potential_lvl+1,exp=exp-'.$cfg['need_exp']
				.' WHERE staff_id='.$staff_id;
		$ret = $DB->exeSql($sql);
		
		// 扣除金钱
		if ($ret) {
			$sql = 'UPDATE user SET coin=coin-'.$cfg['need_coin'].' WHERE uid='.$uid;
			$ret = $DB->exeSql($sql);
		}
		
		
		$result['val'] = (boolean)$ret;
		if ($ret) {
			$DB->commit();
			$result['data'] = self::getInfoById($uid, $staff_id);
		} else {
			$DB->rollBack();
			$result['msg'] = $L['Failure_Update'];
			$str = var_export($DB->errors, true);
			// 记录错误日志
			Log::save('staff_lvl_up', $str);
		}
		
		return $result;
	}
	
	/**
	 * 增加潜力经验
	 * @param int $staff_id
	 * @param int $exp
	 */
	public static function addPotentialExp($staff_id, $exp)
	{
		global $DB, $L, $G;
		
		$staff_id = (int)$staff_id;
		$exp = (int)$exp;
		
		$sql = 'SELECT exp,potential_lvl FROM staff WHERE staff_id='.$staff_id;
		$staffInfo = $DB->getValue($sql);
		
		$cfg = $G['potential_lvl_list'][$staffInfo['potential_lvl']];
		if ($staffInfo['exp'] >= $cfg['need_exp']) {
			return true;
		}
		
		if (($staffInfo['exp']+$exp) > $cfg['need_exp']) {
			$sql = 'UPDATE staff SET exp='.$cfg['need_exp'].' WHERE staff_id='.$staff_id;
		} else {
			$sql = 'UPDATE staff SET exp=exp+'.$exp.' WHERE staff_id='.$staff_id;
		}
		$ret = $DB->exeSql($sql);
		
		$ret !== false  &&  $ret = true;
		
		return $ret;
	}
	
	/**
	 * 给员工增加经验
	 * @param int $uid
	 * @param int|array $staff 员工ID或员工信息
	 * @param int $exp
	 */
//	public static function addExp($uid, $staff, $exp)
//	{
//		global $DB, $L, $G;
//		
//		if (is_int_string($staff)) {
//			$sql = 'SELECT * FROM staff WHERE staff_id='.$staff;
//			$staff = $DB->getValue($sql);
//		}
//		
//		if ($staff['uid']!=$uid) {
//			return array(
//				'val' => false,
//				'msg' => $L['invalid_request']
//			);
//		}
//		
//		$lvl = $staff['lvl'];
//		$newExp = $staff['exp'] + $exp;
//		
//		$upExp = self::$cfg[$lvl]['exp'];
//		
//		if ($lvl == $G['staff_max_lvl']) {
//			$newExp = $upExp;
//		} elseif ($newExp >= $upExp) {//需要升级
//			$lvl++;
//			$newExp -= $upExp;
//			for ($i=$lvl;$i=$G['staff_max_lvl'];$i++) {
//				// 剩余经验不足以再升级
//				if ($newExp < self::$cfg[$lvl]['exp']) {
//					break;
//				} else {// 继续升级
//					$newExp -= self::$cfg[$lvl]['exp'];
//					$lvl++;
//				}
//			}
//		}
//		
//		$addTrainPoint = ($lvl - $staff['lvl'])*$G['add_train_point_per_lvl'];
//		$data = array(
//			'exp' => $newExp,
//			'lvl' => $lvl
//		);
//		if ($addTrainPoint) {
//			$data['max_train_point'] = $staff['max_train_point'] + $addTrainPoint;
//		}
//		$ret = $DB->update('staff', $data, 'staff_id='.$staff['staff_id']);
//		
//		// exeSql只有返回值全等于false时才为处理失败
//		$ret!==false && $ret = true;
//				
//		return $ret;
//	}
	
	/**
	 * 添加培训点
	 * @param int $staff_id
	 * @param int $point_num
	 */
//	public static function addTrainPoint($staff_id, $point_num)
//	{
//		global $DB, $L, $G;
//		
//		$staff_id = (int)$staff_id;
//		$sql = 'SELECT * FROM staff WHERE staff_id='.$staff_id;
//		$staffInfo = $DB->getValue($sql);
//		$staffInfo['train_point'] += $point_num;
//		if ($staffInfo['train_point'] > $staffInfo['max_train_point']) {
//			$staffInfo['train_point'] = $staffInfo['max_train_point'];
//		}
//		$sql = 'UPDATE staff SET train_point='.$staffInfo['train_point']
//			  .' WHERE staff_id='.$staff_id;
//		$ret = $DB->exeSql($sql);
//		if ($ret!==false) $ret = true;
//		
//		return $ret;
//	}
	
	/**
	 * 对员工某个能力进行深造
	 * @param int $uid
	 * @param int $staff_id 员工ID
	 * @param int $abi_id 能力类型
	 */
//	public static function advStudy($uid, $staff_id, $abi_id)
//	{
//		global $DB, $L, $G;
//		
//		$where = 'staff_id='.$staff_id.' and abi_id='.$abi_id;
//		$sql = 'SELECT * FROM staff_data WHERE '.$where;
//		$staffData = $DB->getValue($sql);
//		if (!$staffData || $staffInfo['uid']!=$uid) {
//			return array(
//				'val' => false,
//				'msg' => $L['invalid_request']
//			);
//		}
//		
//		$lvl = $staffData['potential_lvl'];
//		
//		$maxLvl = end($G['potential_lvl_list']);
//		if ($lvl == $maxLvl) {
//			return array(
//				'val' => false,
//				'msg' => $L['potential_is_max_lvl']
//			);
//		}
//		
//		$sql = 'SELECT coin FROM user WHERE uid='.$uid;
//		$coin = $DB->getValue($sql);
//		// 金钱不足
//		if ($coin < $G['potential_lvl_list'][$lvl]['need_coin']) {
//			return array(
//				'val' => false,
//				'msg' => $L['coin_not_enough']
//			);
//		}
//		
//		$cfg = $G['potential_lvl_list'][$lvl+1];
//		
//		$DB->beginTransaction();
//		
//		$sql = 'UPDATE user SET coin=coin-'.$cfg['need_coin'].' WHERE uid='.$uid;
//		$ret = $ret = $DB->exeSql($sql);
//		if (false===$ret) {
//			$DB->rollBack();
//			return array(
//				'val' => false,
//				'msg' => $L['Failure_Update']
//			);
//		}
//		
//		$ret = getRandResult($cfg['success']);
//		// 深造失败
//		if (!$ret) {
//			$ret = getRandResult($cfg['degrade']);
//			// 失败后要降级
//			if ($ret) {
//				$sql = 'UPDATE staff_data SET potential_lvl=potential_lvl-1 WHERE sd_id='.$staffData['sd_id'];
//				$ret = $DB->exeSql($sql);
//			}
//			$DB->commit();
//			return array(
//				'val' => false,
//				'msg' => $L['adv_study_failure']
//			);
//		}
//		
//		// 增加潜力等级
//		$sql = 'UPDATE staff_data SET potential_lvl=potential_lvl+1 WHERE sd_id='.$staffData['sd_id'];
//		$ret = $DB->exeSql($sql);
//	
//		$result['val'] = (boolean)$ret;
//		if (false!==$ret) {
//			$DB->commit();
//			$result['data'] = array(
//				
//			);
//		} else {
//			$DB->rollBack();
//			$result['msg'] = $L['Failure_Insert'];
//			$str = var_export($DB->errors, true);
//			// 记录错误日志
//			Log::save('staff_adv_study', $str);
//		}
//		
//		return $result;
//	}
	
	/**
	 * 培训
	 * @param int $uid
	 * @param int $staff_id 员工ID
	 * @param int $abi_id 能力类型
	 */
	public static function train($uid, $staff_id, $abi_id)
	{
		global $DB, $L, $G;
		
		$staff_id = (int)$staff_id;
		
		$sql = 'SELECT * FROM staff WHERE staff_id='.$staff_id;
		$staffInfo = $DB->getValue($sql);
		if (!$staffInfo || $staffInfo['uid']!=$uid) {
			return array(
				'val' => false,
				'msg' => $L['invalid_request']
			);
		}
		
		$where = 'staff_id='.$staff_id.' and abi_id='.$abi_id;
		$sql = 'SELECT * FROM staff_data WHERE '.$where;
		$staffData = $DB->getValue($sql);
		if (!$staffData) {
			return array(
				'val' => false,
				'msg' => $L['invalid_request']
			);
		}
		
		// 培训次数不足
		if (!$staffInfo['train_times']) {
			return array(
				'val' => false,
				'msg' => $L['train_times_not_enough']
			);
		}
		
		// 金钱是否足够
		$where = ' uid='.$uid;
		$sql = 'SELECT coin FROM user WHERE '.$where;
		$coin = $DB->getValue($sql);
		$needCoin = 100 + pow($staffData['abi_val'], 1.4);
		if ($needCoin > $coin) {
			return array(
				'val' => false,
				'msg' => $L['coin_not_enough']
			);
		}
		
		$DB->beginTransaction();
		
		// 扣除培训次数
		$sql = 'UPDATE staff SET train_times=train_times-1'
			  .' WHERE staff_id='.$staff_id;
		$ret = $DB->exeSql($sql);
		
		// 扣除金钱
		if ($ret) {
			$sql = 'UPDATE user SET coin=coin-'.$needCoin.' WHERE uid='.$uid;
			$ret = $DB->exeSql($sql);
		}
		
		// 增加能力点
		if ($ret) {
			$add_val = rand($G['train_add_val'][0], $G['train_add_val'][1]);
			// 判断是否进行了完美培训
			$perfect_train_rate = $G['perfect_train_rate'][$staffInfo['potential_lvl']];
			if ($perfect_train_rate > 0) {
				$perfect_train = getRandResult($perfect_train_rate);
				if ($perfect_train) {
					$add_val *= 2;
				}
			} else {
				$perfect_train = false;
			}
			if (($staffData['abi_val']+$add_val) > $G['max_abi_val']) {
				$sql = 'UPDATE staff_data SET abi_val='.$G['max_abi_val']
						.' WHERE sd_id='.$staffData['sd_id'];
			} else {
				$sql = 'UPDATE staff_data SET abi_val=abi_val+'.$add_val
						.' WHERE sd_id='.$staffData['sd_id'];
			}
			$ret = $DB->exeSql($sql);
			// 增加总能力值
			if ($ret) {
				$sql = 'UPDATE staff SET total_abi_val=total_abi_val+'.$add_val
						.' WHERE staff_id='.$staff_id;
				$ret = $DB->exeSql($sql);
			}
		}
		
		
		
		$result['val'] = (boolean)$ret;
		if ($ret) {
			$DB->commit();
			$result['data'] = array(
				'staff_info' => self::getInfoById($uid, $staff_id),
				'perfect_train' => $perfect_train
			);
		} else {
			$DB->rollBack();
			$result['msg'] = $L['Failure_Update'];
			$str = var_export($DB->errors, true);
			// 记录错误日志
			Log::save('staff_train', $str);
		}
		
		return $result;
	}
	
	/**
	 * 获取竞技场的列表信息
	 * @param int $uid
	 * @param int $class
	 */
	public static function getArenaList($uid, $class)
	{
		global $DB, $L, $G;
		
		$class = (int)$class;
		// 获取自己员工的信息
		$sql = 'SELECT * FROM staff WHERE uid='.$uid.' and class='.$class;
		$staffInfo = $DB->getValue($sql);
		if (!$staffInfo) {
			return array(
				'val' => false,
				'msg' => $L['invalid_request']
			);
		}
		$today = strtotime('today');
		// 每天更新PK次数
		$last_pk_time = User::read($uid, 'last_pk_time');
		if ($last_pk_time < $today) {
			$sql = 'UPDATE user SET remain_pk_times='.$G['pk_times_per_day']
					.', last_pk_time='.$today.' WHERE uid='.$uid;
			$ret = $DB->exeSql($sql);
		}
		$staffInfo['remain_pk_times'] = $G['pk_times_per_day'];
		$staffInfo['last_pk_time'] = $last_pk_time;
		
		// 获取可PK的竞争对手的列表
		$minAbi = $staffInfo['total_abi_val'] * $G['pk_min_abi'];
		$maxAbi = $staffInfo['total_abi_val'] * $G['pk_max_abi'];
		
		$sql = 'SELECT staff_id, uid, total_abi_val FROM `staff` WHERE class='.$class.' AND
				total_abi_val>='.$minAbi.' and total_abi_val<='.$maxAbi.'
				AND uid<>'.$uid.' ORDER BY RAND()
				LIMIT 6';
		$list = $DB->getList($sql);
		// 可PK人数不足,补充
		if (count($list) < 6) {
			$size = 6 - count($list);
			$sql = 'SELECT staff_id, uid, total_abi_val FROM `staff` WHERE class='.$class.' AND
					(total_abi_val<'.$minAbi.' OR total_abi_val>'.$maxAbi.')
					AND uid<>'.$uid.' ORDER BY RAND()
					LIMIT '.$size;
			$tmp = $DB->getList($sql);
			if ($tmp) {
				$list = array_merge($list, $tmp);
			}
		}
		
		$uidList = array();
		foreach ($list as $v) {
			$uidList[] = $v['uid'];
		}
		
		// 获取所有对手用户名称
		$sql = 'SELECT uid,nickname,sex FROM user WHERE uid IN ('.join(',', $uidList).')';
		$tmpList = $DB->getList($sql);
		$userList = array();
		foreach ($tmpList as $v) {
			$userList[$v['uid']] = array(
				'nickname' => $v['nickname'],
				'sex' => $v['sex'],
			);
		}
		
		foreach ($list as $k=>$v) {
			$list[$k]['nickname'] = $userList[$v['uid']]['nickname'];
			$list[$k]['sex'] = $userList[$v['uid']]['sex'];
		}
		
		$result['val'] = true;
		$result['data'] = array(
			'staff_info'=> $staffInfo,
			'list' => $list,
		);
		
		return $result;
	}
	
	/**
	 * 员工PK
	 * @param int $uid
	 * @param int $staff_id
	 * @param int $target_staff_id
	 */
	public static function pk($uid, $staff_id, $target_staff_id)
	{
		global $DB, $L, $G;
		
		$staff_id = (int)$staff_id;
		$target_staff_id = (int)$target_staff_id;
		$today = strtotime('today');
		
		// 获取自己员工的信息
		$staffInfo = self::getInfoById($uid, $staff_id);
		if (!$staffInfo || $staffInfo['uid']!=$uid) {
			return array(
				'val' => false,
				'msg' => $L['invalid_request']
			);
		}
		
		// 获取对手员工的信息
		$targetStaffInfo = self::getInfoById($uid, $target_staff_id);
		if (!$targetStaffInfo) {
			return array(
				'val' => false,
				'msg' => $L['invalid_request']
			);
		}
		
		$user = User::read($uid, 'last_pk_time,remain_pk_times');
		if (!$user['remain_pk_times'] && $user['last_pk_time'] >= $today) {
			return array(
				'val' => false,
				'msg' => $L['remain_pk_times_not_enough']
			);
		}
		
		// PK过程数据
		$process = array();
		$selfTotalScore		= 0;// 自己总评分
		$targetTotalScore	= 0;// 对手总评分
		
		// 更新的sql语句 
		$updateSql = '';
		// 每个回合开始PK
		for ($i=1; $i<=$G['staff_pk_bout']; $i++) {
			$selfScore = (int)round(round($staffInfo['total_abi_val'] * $staffInfo['state_val']/100 
							* rand($G['pk_score_range'][0], $G['pk_score_range'][1])/100));
			$targetScore = (int)round(round($targetStaffInfo['total_abi_val'] * $targetStaffInfo['state_val']/100
							* rand($G['pk_score_range'][0], $G['pk_score_range'][1])/100));
			
			$item 		= $staffInfo['card_list'][$i];
			$targetItem	= $targetStaffInfo['card_list'][$i];
			$itemId			= $item['item_id'];
			$targetItemId	= $targetItem['item_id'];
			if ($item['lvl'] == 0) {
				$lvl = 0;
			} elseif (isset($item['bag_id']) && isset($item['use_times'])) {
				if ($item['use_times']) {
					$lvl =  $item['lvl'];
					$item['use_times'] -= 1;
					$bag_id = $item['bag_id'];
					// 当前使用完,卡片 使用次数为0,则同时删除,不为0,则只减少使用次数
					if ($item['use_times']) {
						$attr = array('use_times' => $item['use_times']);
						$attr = json_encode($attr);
						$updateSql .= 'UPDATE bag SET attr=\''.$attr.'\' WHERE bag_id='.$bag_id.';';
					} else {
						$updateSql .= 'DELETE FROM bag WHERE bag_id='.$bag_id.';';
						$updateSql .= 'UPDATE `staff` SET `card'.$i.'`='.$itemId
										.' WHERE  `staff_id` ='.$item['staff_id'].';';
						$content = sprintf(
											$L['mail_staff_card_be_deleted_with_no_use_times'],
											$item['title']
									);
						$ret = Mail::send(0, User::getNickname($uid), $content, 1);
					}
				} else {// 使用次数不足,换用0级卡片
					$lvl = 0;
					// 同时销毁次数为0的卡片
					$updateSql .= 'DELETE FROM bag WHERE bag_id='.$item['bag_id'].';';
					$content = sprintf(
										$L['mail_staff_card_be_deleted_with_no_use_times'],
										$item['title']
								);
					$ret = Mail::send(0, User::getNickname($uid), $content, 1);
				}
			}
			
			if ($targetItem['lvl'] == 0) {
				$targetLvl = 0;
			} elseif (isset($targetItem['use_times']) ) {
				if ($targetItem['use_times']) {
					$lvl =  $targetItem['lvl'];
				} else {
					$lvl = 0;
				}
			}
			
			// 比较双方卡片
			if ($itemId == $targetItemId) {//平手,跳过
				// 当前回合最终评分
				$selfCardScore   = 0;
				$targetCardScore = 0;
			} elseif ($G['card_pk_result'][$itemId] == $targetItemId) {//赢了对手
				// 胜利方胜利参数
				$winParam = $G['card_lvl_attr'][$lvl]['win'];
				// 失败方失败参数
				$loseParam = $G['card_lvl_attr'][$targetLvl]['lose'];
				$reduceScore = round($targetScore * ($winParam*(1-$loseParam)));
				// 当前回合最终评分
				$selfCardScore   = 0;
				$targetCardScore = -$reduceScore;
			} else {//输了
				// 胜利方胜利参数
				$winParam = $G['card_lvl_attr'][$targetLvl]['win'];
				// 失败方失败参数
				$loseParam   = $G['card_lvl_attr'][$lvl]['lose'];
				$reduceScore = round($selfScore * ($winParam*(1-$loseParam)));
				// 当前回合最终评分
				$selfCardScore   = -$reduceScore;
				$targetCardScore = 0;
			}
			
			$selfBoutScore = $selfScore + $selfCardScore;
			$targetBoutScore = $targetScore + $targetCardScore;
			$process[$i] = array(
				'self_score'		=> $selfScore,
				'target_score'		=> $targetScore,
				'self_card_score'	=> $selfCardScore,
				'target_card_score'	=> $targetCardScore,
				'self_bout_score'	=> $selfBoutScore,
				'target_bout_score'	=> $targetBoutScore,
				'self_card'			=> $item['title'].'Lv'.$item['lvl'],
				'target_card'		=> $targetItem['title'].'Lv'.$targetItem['lvl'],
			);
			
			// 总分
			$selfTotalScore		+= $selfBoutScore;
			$targetTotalScore	+= $targetBoutScore;
		}
		// PK结束
		
		$selfTotalScore		= round($selfTotalScore);
		$targetTotalScore	= round($targetTotalScore);
		$totalScore = array($selfTotalScore, $targetTotalScore);
		
		if ($selfTotalScore > $targetTotalScore) {// 胜
			$pkResult = 'win';
		} elseif ($selfTotalScore == $targetTotalScore) {//平
			$pkResult = 'deuce';
		} else {// 负
			$pkResult = 'loss';
		}
		
		C('build/making');
		$classSign = $G['make_class_type_sign_list'][$staffInfo['class']];
		// 制造子类型列表
		$makeClass = $G[$classSign];
		$prizeList = array();
		$prizeNumList = array();
		for ($i=0; $i<$G['pk_prize_choice_num']; $i++) {
			$k = getRandResult($G['pk_prize_rate'], array_sum($G['pk_prize_rate']));
			$prizeCfg = $G['pk_prize'][$k];
			if (isset($prizeNumList[$k])) {
				$prizeNumList[$k]++;
				if ($prizeNumList[$k] == $G['pk_prize_max_num']) {
					//该物品已被出现三次，不再被奖励
					unset($G['pk_prize'][$k]);
					unset($G['pk_prize_rate'][$k]);
				}
			} else {
				$prizeNumList[$k] = 1;
			}
			$detailRandList = array();
			$rndRateVal = 0;
			foreach ($prizeCfg['detail'] as $key => $value) {
				$rndRateVal += $value[$pkResult];
				$detailRandList[$key] = $rndRateVal;
			}
			CI_ONCE('build/making');
			if ($k == 'sec_mat') {
				$classSign = $G['make_class_type_sign_list'][$staffInfo['class']];
				// 只能对应制造类型下取辅材
				$cfgList = $G[$classSign.'_sec_mat_item'];
				$item_id = array_rand($cfgList);
				$cfg = $cfgList[$item_id];
				$lvl = 0;
				$num = 1;
				$quality = getRandResult($detailRandList);
				$attr = '';
				
			} elseif ($k == 'equip') {
				$cfgList = C('item/equip');
				$equipList = array();
				$plvl = $staffInfo['potential_lvl'];
				foreach ($cfgList as $key=>$val) {
					if ($val['class'] != $staffInfo['class'] || $val['lvl'] < ($plvl-3) || $val['lvl'] > ($plvl+1)) {
						continue;
					}
					$equipList[$key] = $val;
				}
				$item_id = array_rand($equipList);
				$cfg = $cfgList[$item_id];
				$lvl = $cfg['lvl'];
				$num = 1;
				$color = getRandResult($detailRandList);
				$part = $cfg['part'];
				
				$tmp = $makeClass;
				$attr = array();
				// 根据装备颜色确定要生成的属性个数
				for ($ii=0; $ii<$G['equip_color_attr_num'][$color]; $ii++) {
					$_k = array_rand($tmp);
					$_info = $tmp[$_k];
					unset($tmp[$_k]);
					$abi_id = $_info['item_id'];
					$abi_val = rand($cfg['add_abi'][$color][0], $cfg['add_abi'][$color][1]);
					$attr[$abi_id] = $abi_val;
				}
				$attr = json_encode($attr);
				
			} elseif ($k == 'gem') {
				$cfgList = C('item/gem');
				// 只能取对应制造类型的宝石
				foreach ($cfgList as $item_id => $gem) {
					if ($gem['class'] == $staffInfo['class']) {
						break;
					}
				}
				$cfg = $gem;
				$lvl = getRandResult($detailRandList);
				$num = 1;
				$key = array_rand($cfg['add_attr_type']);
				$abi_id = $cfg['add_attr_type'][$key];
				$abi_val = $G['gem_lvl_val'][$lvl];
				$attr = '{"'.$abi_id.'":"'.$abi_val.'"}';
				
			} elseif ($k == 'card') {
				$cfgList = C('item/other');
				foreach ($cfgList as $key=>$val) {
					if ($val['item_type'] != 54) {
						unset($cfgList[$key]);
					}
				}
				$item_id = array_rand($cfgList);
				$cfg = $cfgList[$item_id];
				$lvl = getRandResult($detailRandList);
				$num = 1;
				$attr = array(
					'use_times' => rand($cfg['use_times'][0], $cfg['use_times'][1])
				);
				$attr = json_encode($attr);
				
			} elseif ($k == 'coin') {
				$cfgList = C('item/other');
				$item_id = 65535;
				$cfg = $cfgList[65535];
				$lvl = 0;
				$num = getRandResult($detailRandList);
				$attr = '';
			}
			$tmp = array(
				'item_id' => $item_id,
				'title' => $cfg['title'],
				'lvl'	=> $lvl,
				'type'	=> $cfg['item_type'],
				'num'	=> $num,
				'attr'	=> $attr,
			);
			if ($k == 'sec_mat') {
				$tmp['quality'] = $quality;
			} elseif ($k == 'equip') {
				$tmp['color'] = $G['color_id'][$color];
				$tmp['part'] = $part;
			} elseif ($k == 'gem') {
				$tmp['color'] = $cfg['color'];
			}
			$prizeList[$i+1] = $tmp;
		}
		
		$DB->beginTransaction();
		
		$now = time();
		
		$targetStaffInfo['target_nickname'] = User::read($targetStaffInfo['uid'], 'nickname');
		$data = array(
			'uid'			=> $uid,
			'class'			=> $staffInfo['class'],
			'staff_id'		=> $staff_id,
			'staff'			=> json_encode($staffInfo),
			'target_staff'	=> json_encode($targetStaffInfo),
			'process'		=> json_encode($process),
			'total_score'	=> json_encode($totalScore),
			'prize_list'	=> json_encode($prizeList),
			'create_time'	=> $now,
		);
		$ret = $DB->insert('staff_pk_log', $data);
		$spl_id = $DB->lastInsertId();
		
		// 如果有要更新的SQL语句,则执行
		if ($updateSql) {
			$ret = $DB->exeSql($updateSql);
			if ($ret !== false ) {
				$ret = true;
			}
		}
		
		// 删除半小时前(配置)的奖励记录
		if ($ret) {
			$sql = 'DELETE FROM staff_pk_log WHERE create_time<='.($now - $G['pk_log_save_seconds']);
			$ret = $DB->exeSql($sql);
			if ($ret !== false ) {
				$ret = true;
			}
		}
		
		// 保存对方被挑战记录
		if ($ret) {
			$data = array(
				'spl_id'		=> $spl_id,
				'class'			=> $staffInfo['class'],
				'uid'			=> $targetStaffInfo['uid'],
				'from_uid'		=> $uid,
				'from_username'	=> $_SESSION['username'],
				'result'		=> $G['pk_result_sign_id'][$pkResult],
				'pk_time'		=> $now
			);
			$ret = $DB->insert('staff_bepk_log', $data);
		}
		
		// PK获胜培训次数+1
		if ($ret && $pkResult == 'win') {
			$sql= 'UPDATE staff SET train_times=train_times+1 WHERE staff_id='.$staff_id;
			$ret = $DB->exeSql($sql);
		}
		
		// PK次数-1
		if ($ret) {
			$sql = 'UPDATE user SET remain_pk_times=remain_pk_times-1 WHERE uid='.$uid;
			$ret = $DB->exeSql($sql);
		}
		
		
		$result['val'] = (boolean)$ret;
		if ($ret) {
			$DB->commit();
			$result['data'] = array(
				'spl_id'		=> $spl_id,
				'process'		=> $process,
				'total_score'	=> $totalScore,
				'prize_list'	=> $prizeList,
			);
		} else {
			$DB->rollBack();
			$result['msg'] = $L['Failure_Update'];
			$str = var_export($DB->errors, true);
			// 记录错误日志
			Log::save('staff_pk', $str);
		}
		
		return $result;
	}
	
	/**
	 * 获取PK记录列表
	 * @param int $uid
	 * @param int $staff_id
	 */
	public static function getPkLogList($uid, $staff_id)
	{
		global $DB, $L, $G;
		
		$staff_id = (int)$staff_id;
		
		$sql = 'SELECT uid FROM staff WHERE staff_id='.$staff_id;
		$_uid = $DB->getValue($sql);
		if ($_uid != $uid) {
			return false;
		}
		
		// 删除30分钟前的记录
		$where = 'create_time<'.(time()-1800);
		$DB->delete('staff_pk_log', $where);
		
		$sql = 'SELECT * FROM staff_pk_log WHERE staff_id='.$staff_id;
		$list = $DB->getList($sql);
	
		$itemList = C('item/item_list');
		
		foreach ($list as $k => $v) {
			$v['staff']			= json_decode($v['staff'], true) ;
			$v['target_staff']	= json_decode($v['target_staff'], true) ;
			$v['process']		= json_decode($v['process'], true) ;
			$v['total_score']	= json_decode($v['total_score'], true) ;
			$v['prize_list']	= json_decode($v['prize_list'], true) ;
			foreach ($v['process'] as $kk => $vv) {
				$v['process_title'][$kk] = $itemList[$kk]['title'];
			}
			$list[$k] = $v;
		}
		
		return $list;
	}
	
	/**
	 * 获取PK消息
	 * @param int $uid
	 */
	public static function getPkMessage($uid, $class=null)
	{
		global $DB, $L, $G;
	
		// 删除30分钟前的记录
		$where = 'create_time<'.(time()-1800);
		$DB->delete('staff_pk_log', $where);
		// 被PK记录
		$where = 'pk_time<'.(time()-1800);
		$DB->delete('staff_bepk_log', $where);
	
		$itemList = C('item/item_list');
		
		// PK别人的记录
		$sql = 'SELECT * FROM staff_pk_log WHERE uid='.$uid;
		if ($class) {
			$sql .= ' AND class='.(int)$class;
		}
		$list = $DB->getList($sql);
		
		$msgList = array();
		$targetUidList = array();
		
		foreach ($list as $k => $v) {
			$v['staff']			= json_decode($v['staff'], true) ;
			$v['target_staff']	= json_decode($v['target_staff'], true) ;
			$v['process']		= json_decode($v['process'], true) ;
			$v['total_score']	= json_decode($v['total_score'], true) ;
			$v['prize_list']	= json_decode($v['prize_list'], true) ;
			foreach ($v['process'] as $kk => $vv) {
				$v['process_title'][$kk] = $itemList[$kk]['title'];
			}
			if ($v['total_score'][0] > $v['total_score'][1]) {
				$result = 'win';
			} elseif ($v['total_score'][0] == $v['total_score'][1]) {
				$result = 'deuce';
			} else {
				$result = 'loss';
			}
			$targetUidList[] = $v['target_staff']['uid'];
			$msgList[] = array(
				'spl_id'		=> $v['spl_id'],
				'target_uid'	=> $v['target_staff']['uid'],
				'result'		=> $result,
				'pk_time'		=> $v['create_time']
			);
		}
		
		// 查找所有被PK玩家的名称
		if ($targetUidList) {
			$sql = 'SELECT uid,username FROM user WHERE uid IN ('.join(',', $targetUidList).')';
			$arr = $DB->getList($sql);
			$tmp = array();
			foreach ($arr as $v) {
				$tmp[$v['uid']] = $v['username'];
			}
		}
		
		if ($msgList) {
			foreach ($msgList as $k=>$v) {
				$msgList[$k]['target_username'] = $tmp[$v['target_uid']];
			}
		}
		
		// 被PK记录
		$sql = 'SELECT * FROM staff_bepk_log WHERE uid='.$uid;
		if ($class) {
			$sql .= ' AND class='.(int)$class;
		}
		$arr = $DB->getList($sql);
		foreach ($arr as $v) {
			$msgList[] = array(
				'spl_id'		=> $v['spl_id'],
				'from_uid'		=> $v['from_uid'],
				'from_username'	=> $v['from_username'],
				'result'		=> $G['pk_result_sign_list'][$v['result']],
				'pk_time'		=> $v['pk_time']
			);
		}
		
		return $msgList;
	}
	
	/**
	 * 获取PK奖励信息
	 * @param int $uid
	 * @param int $spl_id
	 */
	public static function getPkResultInfo($uid, $spl_id)
	{
		global $DB, $L, $G;
		
		$spl_id = (int)$spl_id;
		
		$sql = 'SELECT * FROM staff_pk_log WHERE spl_id='.$spl_id;
		$splInfo = $DB->getValue($sql);
		if (!$splInfo) {
			return false;
		}
		
		$splInfo['staff']		= json_decode($splInfo['staff'], true);
		$splInfo['target_staff']= json_decode($splInfo['target_staff'], true);
		
		if ($splInfo['staff']['uid']!=$uid && $splInfo['uid']!=$uid) {
			return false;
		}
		
		$splInfo['process']		= json_decode($splInfo['process'], true);
		$splInfo['total_score']	= json_decode($splInfo['total_score'], true);
		$splInfo['prize_list']	= json_decode($splInfo['prize_list'], true);
		
		if (isset($splInfo['target_staff']['target_nickname'])) {
			$splInfo['target_nickname'] = $splInfo['target_staff']['target_nickname'];
			unset($splInfo['target_staff']['target_nickname']);
		}
		
		
		return $splInfo;
	}
	
	/**
	 * 获取PK奖励
	 * @param int $uid
	 * @param int $spl_id
	 * @param array $no_choice 放弃的物品
	 */
	public static function getPkPrize($uid, $spl_id, $no_choice)
	{
		global $DB, $L, $G;
		
		$splInfo = self::getPkResultInfo($uid, $spl_id);
		if ($splInfo === false) {
			return array(
				'val' => false,
				'msg' => $L['invalid_request']
			);
		} elseif (!$splInfo) {
			return array(
				'val' => false,
				'msg' => $L['Failure_Read']
			);
		} elseif (!$splInfo['prize_list']) {
			return array(
				'val' => false,
				'msg' => $L['invalid_request']
			);
		} elseif ($splInfo['uid'] != $uid) {
			return array(
				'val' => false,
				'msg' => $L['invalid_request']
			);
		}/* elseif ($splInfo['total_score'][0] < $splInfo['total_score'][1]) {
			return array(
				'val' => false,
				'msg' => $L['invalid_request']
			);
		}*/
		
		$noChoiceNum = sizeof($no_choice);
		if ($noChoiceNum > 4) {
			return array(
				'val' => false,
				'msg' => $L['invalid_request']
			);
		}
		
		$prize_list = $splInfo['prize_list'];
		// 从抽取的奖品列表中丢弃不参与抽取的物品,同时扣除道具
		if ($no_choice) {
			foreach ($no_choice as $v) {
				if (!is_int_string($v)) {
					return array(
						'val' => false,
						'msg' => $L['invalid_request']
					);
				}
				unset($prize_list[$v]);
			}
		}
		
		$needTicket = $G['get_pk_prize_nochioce_ticket'][$noChoiceNum];
		
		// 点券不足
		$sql = 'SELECT ticket FROM user WHERE uid='.$uid;
		$ticket = $DB->getValue($sql);
		if ($ticket < $needTicket) {
			return array(
				'val' => false,
				'msg' => $L['user_ticket_not_enough']
			);
		}
		
		$nenner = 0;// 分母
		$randList = array();
		foreach ($prize_list as $key => $value) {
			$val = $G['pk_prize_base'][$value['type']];
			$nenner += $val;
			$randList[$key] = $val;
		}
		$key = getRandResult($randList, $nenner);
		$info = $prize_list[$key];
		
		$DB->beginTransaction();
		
		// 点券是否已消耗,默认没有,当增加金钱时,顺便消耗(减少一个UPDATE操作)
		$hadConsumeTicket = false;
		if ($info['type'] == 99) {//金钱
			$hadConsumeTicket = true;
			$data = array(
				'coin' => $info['num'], 
				'title' => $info['title']
			);
			$sql = 'UPDATE user SET coin=coin+'.$info['num'].', ticket=ticket-'.$needTicket.' WHERE uid='.$uid;
			$ret = $DB->exeSql($sql);
			$attr = '';
		} elseif ($info['type'] == 51) {//辅材进入仓库
			$data = array(
				'item_id'	=> $info['item_id'],
				'item_type' => $info['type'],
				'title'		=> $info['title'],
				'num'		=> 1,
				'stack'		=> 1,
				'quality'	=> $info['quality'],
				'lvl'		=> $info['lvl'],
			);
			$ret = Depot::in($uid, $data);
			if ($ret['val']) {
				$depot_id = $ret['data']['depot_id'];
			} else {
				$msg = $ret['msg'];
			}
			$ret = $ret['val'];
			$attr = '';
		} else {// 装备宝石进入背包
			!isset($info['color']) && $info['color'] = 0;
			!isset($info['part']) && $info['part'] = 0;
			$inlay = '';
			if ($info['type'] == 52) {// 宝石
				$attr = $info['attr'];
			} elseif ($info['type'] == 53) {//装备
				$attr = array(
					'base'	 => $info['attr'],
					'result' => $info['attr'],
				);
				$equipCfgList = C('item/equip');
				$colorSign = $G['id_color'][$info['color']];
				$slot_num = $G['equip_color_slot_num'][$colorSign];
				$inlay = array();
				for ($i=1; $i<=$slot_num; $i++) {
					$inlay[$i] = array();
				}
				$inlay = json_encode($inlay);
			} elseif ($info['type'] == 54) {//卡片
				
			}
			$data = array(
				'item_id'	=> $info['item_id'],
				'item_type' => $info['type'],
				'title'		=> $info['title'],
				'num'		=> 1,
				'quality'	=> 0,
				'stack'		=> 0,
				'lvl'		=> $info['lvl'],
				'color'		=> $info['color'],
				'part'		=> $info['part'],
				'inlay'		=> $inlay,
				'attr'		=> $info['attr'],
			);
			$ret = Bag::in($uid, $data);
			if ($ret) {
				$bag_id = $ret;
			} else {
				$msg = Bag::$msg;
			}
		}
		
		// 消耗点券
		if ($ret && !$hadConsumeTicket && $needTicket>0) {
			$sql = 'UPDATE user SET ticket=ticket-'.$needTicket.' WHERE uid='.$uid;
			$ret = $DB->exeSql($sql);
			if (false !== $ret) {
				$ret = true;
			}
		}
		
		// 清空奖励信息
		if ($ret) {
			$sql = 'UPDATE staff_pk_log SET prize_list=\'\' WHERE spl_id='.$spl_id;
			$ret = $DB->exeSql($sql);
			if (false !== $ret) {
				$ret = true;
			}
		}
		
		
		$result['val'] = (boolean)$ret;
		if ($ret) {
			$DB->commit();
			if (isset($depot_id)) {
				$data['depot_id'] = $depot_id;
			} elseif (isset($bag_id)) {
				$data['bag_id'] = $bag_id;
			}
			$data['attr'] = $attr;
			$result['data'] = $data;
		} else {
			$DB->rollBack();
			if (isset($msg)) {
				$result['msg'] = $msg;
			} else {
				$result['msg'] = $L['Failure_Update'];
			}
			$str = var_export($DB->errors, true);
			// 记录错误日志
			Log::save('staff_get_pk_prize', $str);
		}
		return $result;
	}
}




